package pl.edu.agh.inpema.components.receivers.emailReceiver;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;

import org.apache.log4j.Logger;

import pl.edu.agh.inpema.components.receivers.randomReceiver.RandomReceiver;
import pl.edu.agh.inpema.core.components.ReceiverUtil;
import pl.edu.agh.inpema.core.model.Message;
import pl.edu.agh.inpema.core.model.Receiver;

public class EmailReceiver extends Thread implements Receiver {

	private static final String[] messageFieldTypes = { FIELD_IP, FIELD_DATE,
			FIELD_TEXT };
	private static final String POP3 = "pop3";
	private static final String INBOX = "INBOX";

	private boolean isRunning = false;
	private boolean error = false;
	private static Logger logger = Logger.getLogger(EmailReceiver.class);
	private ReceiverUtil receiverUtil;

	private String host;
	private String login;
	private String password;

	public void setReceiverUtil(ReceiverUtil util) {
		this.receiverUtil = util;
	}

	public ReceiverUtil getReceiverUtil() {
		return this.receiverUtil;
	}

	public void run() {
		logger.info(this.receiverUtil.getReceiverName() + ": starting...");

		try {
			Session session = Session.getInstance(new Properties());
			Store store = session.getStore(POP3);
			store.connect(host, login, password);

			Folder fldr = store.getFolder(INBOX);
			fldr.open(Folder.READ_WRITE);
			int count = fldr.getMessageCount();
			logger.info(this.receiverUtil.getReceiverName() + ": " + count
					+ " total messages");

			while (this.isRunning) {
				count--;
				if (count == 0) {
					logger.info(this.receiverUtil.getReceiverName()
							+ ": no more data");
					this.isRunning = false;
				} else {
					javax.mail.Message msg = fldr.getMessage(count);
					Date date = msg.getSentDate();
					Address[] from = msg.getFrom();
					String subject = msg.getSubject();

					Object o = msg.getContent();
					if (o instanceof String) {
						// System.out.println("**This is a String Message**");
						// System.out.println((String)o);
						Map<String, String> messageFields = new HashMap<String, String>();
						messageFields.put(Message.FIELD_IP, from[0].toString());
						if (date != null) {
						messageFields.put(Message.FIELD_DATE, ""
								+ date.getTime());
						} else {
							messageFields.put(Message.FIELD_DATE, "");
						}
						messageFields.put(Message.FIELD_TEXT, (String) o);

						this.receiverUtil.addMessage(from[0].toString(), messageFields);
						logger.info(this.receiverUtil.getReceiverName()
								+ ": send message");
					}
				}	
			}
			fldr.close(false);
			store.close();
		} catch (Exception e) {
			error = true;
			e.printStackTrace();
		}
		logger.info(this.receiverUtil.getReceiverName() + ": finishing...");
	}

	public void startGathering() {
		this.isRunning = true;
		this.start();
	}

	public boolean stopGathering() {
		this.isRunning = false;
		return this.error;
	}

	public boolean isGatheringRunning() {
		return this.isRunning;
	}

	public String[] getMessageFieldTypes() {
		return messageFieldTypes;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
